package com.ruoyi.common.utils;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.utils.file.FileUtils;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.*;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

public class OcrUtil {

    private static String secretId = "AKIDSkmX2GDtJSMzLRItDG4exzjESQ8aleGb";

    private static String secretKey = "6vSiiRt3xauxiCPN6ankRs33zvhFafW8";

    private static Logger logger = LoggerFactory.getLogger(OcrUtil.class);

    //转账银行名称
    private static String fromBankName[] = {"Beneficiary Name","From Account Name"};
    //转账银行卡号
    private static String fromAccountNo[] = {"Pay From Account","From Account Number"};
    //转账日期
    private static String tranDate[] = {"Transaction Date","Payment Date"};
    //转账金额
    private static String tranAmount[] = {"Amount"};
    //转账单号
    private static String transNo[] = {"Reference ID","Channel Reference ID"};
    //收款银行名称
    private static String toBankName[] = {"Bank Name"};
    //收款账号名称
    private static String toAccountName[] = {"nickname/account No","Account Name"};
    //收款转账银行卡号
    private static String toAccountNo[] = {"Beneficiary Accountnumber","Account Number","Beneficiary Account number","To Account Number"};
    //收款银行IFSC
    private static String toIfscCode[] = {"IFSC Code"};

    public static void main(String[] args){
        //OcrUtil.parseImage("https://images.tongkeer.com/photo_2023-11-24_10-18-23.jpg");
        //OcrUtil.parseImage("https://images.tongkeer.com/photo_2023-11-24_19-39-10.jpg");
        //OcrUtil.parseImage("https://images.tongkeer.com/photo_2023-11-24_19-39-10.jpg");
        //String imageFilePath = "d://test.png";
        String imageFilePath = "d://1.png";
        //String imageFilePath = "d://2.png";
        //String imageFilePath = "d://3.png";
        //String imageFilePath = "d://4.png";
        try {
            File file = new File(imageFilePath);
            BufferedImage bufferedImage = ImageIO.read(file);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
            byte[] bytes = byteArrayOutputStream.toByteArray();
            System.out.println("image code="+OcrUtil.parseCodeImage(bytes));
            // 处理字节数组中的图像
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public static TransVo parseImage(byte[] imageContent) {
        TransVo vo = null;
        /*
        vo = new TransVo();
        vo.setToAccountNo("112223333");
        vo.setAmount("30000");
        return vo;
         */
        try{
            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            Credential cred = new Credential(secretId, secretKey);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ocr.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            OcrClient client = new OcrClient(cred, "ap-guangzhou", clientProfile);
            //OcrClient client = new OcrClient(cred, "na-toronto", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            BankSlipOCRRequest req = new BankSlipOCRRequest();
            //req.setImageUrl(imageUrl);
            req.setImageBase64(convertImageToBase64(imageContent,"png"));
            // 返回的resp是一个VatInvoiceOCRResponse的实例，与请求对象对应
            BankSlipOCRResponse resp = client.BankSlipOCR(req);
            if (resp.getBankSlipInfos() != null && resp.getBankSlipInfos().length>0){
                BankSlipInfo[] banks = resp.getBankSlipInfos();
                vo = new TransVo();
                vo.setAmount(getValue(banks,tranAmount));
                if (StringUtils.isNotEmpty(vo.getAmount()) && vo.getAmount().startsWith("2,")){
                    vo.setAmount(vo.getAmount().substring(2));
                }
                if (StringUtils.isNotEmpty(vo.getAmount()) && vo.getAmount().contains(",")){
                    vo.setAmount(vo.getAmount().replaceAll(",",""));
                }
                vo.setFromAccountNo(getValue(banks,fromAccountNo));
                vo.setFromBankName(getValue(banks,fromBankName));
                vo.setToAccountNo(getValue(banks,toAccountNo));
                //vo.setToBankName(getValue(banks,toBankName));
                //vo.setToIFSC(getValue(banks,toIfscCode));
                vo.setTransDate(getValue(banks,tranDate));
                vo.setTransNo(getValue(banks,transNo));
                //vo.setToAccountName(getValue(banks,toAccountName));
                logger.debug("识别转账凭证如下===>{}",JSON.toJSONString(vo));
            }
            // 输出json格式的字符串回包
            //System.out.println(BankSlipOCRResponse.toJsonString(resp));
        } catch (Exception e) {
            vo = null;
            logger.debug("识别转账凭出错===>{}",JSON.toJSONString(e));
        }
        return vo;
    }


    public static String parseCodeImage(byte[] imageContent) {
        try {
            return YdmVerify.commonVerify(imageContent);
        }catch (Exception e){
            e.printStackTrace();
            return "00000";
        }

        /*
        try{
            Credential cred = new Credential(secretId, secretKey);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ocr.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            OcrClient client = new OcrClient(cred, "ap-guangzhou", clientProfile);
            //OcrClient client = new OcrClient(cred, "na-toronto", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            vo = "";
            GeneralEfficientOCRRequest req2 = new GeneralEfficientOCRRequest();
            req2.setImageBase64(convertImageToBase64(imageContent,"png"));
            GeneralEfficientOCRResponse resp2 = client.GeneralEfficientOCR(req2);
            if (resp2.getTextDetections() != null){
                for(TextDetection td:resp2.getTextDetections()){
                    vo += td.getDetectedText();
                }
                logger.debug("识别图片验证码===>{}",vo);
            }

        } catch (Exception e) {
            vo = null;
            logger.debug("识别转账凭出错===>{}",JSON.toJSONString(e));
        }
        if (StringUtils.isNotEmpty(vo)){
            vo = vo.replaceAll(" ","");
        }
        return vo;
        */
    }

    private static String getValue(BankSlipInfo[] banks,String[] names){
        String rst = "";
        for (BankSlipInfo bank:banks) {
            for (String name:names) {
                if (bank.getName().toLowerCase().startsWith(name.toLowerCase())){
                    rst = bank.getValue();
                    break;
                }
            }
        }
        return rst;
    }

    /**
     * 将网络路径图片转为base64的格式
     * @param content 图片内容
     * @param photoType 响应的格式(png,jpg,ico等)
     * @throws Exception
     */
    public static String convertImageToBase64(byte[] content, String photoType) throws Exception {
        // 对字节数组Base64编码
        Base64.Encoder encoder = Base64.getEncoder();
        return "data:image/" + photoType + ";base64," + encoder.encodeToString(content);
    }

}
